//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using OpenLS.Core;
using OpenLS.Spreadsheet.UI.Internals;
using OpenLS.UI;

namespace OpenLS.Spreadsheet.UI
{
    static class GridUndoRedo
    {
        public static void EnableCommands(UIElement grid)
        {
            grid.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo,
                onUndo, onCanUndo));
            grid.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo,
                onRedo, onCanRedo));
        }


        static void onUndo(object sender, ExecutedRoutedEventArgs args)
        {
            Workbook wb = getWorkbook(sender);
            if (wb == null)
                return;
            if (!wb.UndoEnabled)
                return;
            var a = (IUndoUnit)args.Parameter;
            wb.Undo(a);
        }
        private static Workbook getWorkbook(object sender)
        {
            return SpreadsheetElement.GetWorkbook((DependencyObject)sender);
        }
        static void onRedo(object sender, ExecutedRoutedEventArgs args)
        {
            Workbook wb = getWorkbook(sender);
            if (wb == null || !wb.UndoEnabled)
                return;
            var a = (IUndoUnit)args.Parameter;
            wb.Redo(a);
        }
        static void onCanUndo(object sender, CanExecuteRoutedEventArgs args)
        {
            Workbook wb = getWorkbook(sender);
            if (wb == null)
                return;
            args.CanExecute = wb.CanUndo;
        }
        static void onCanRedo(object sender, CanExecuteRoutedEventArgs args)
        {
            Workbook wb = getWorkbook(sender);
            if (wb == null)
                return;
            args.CanExecute = wb.CanRedo;
        }


    }
}
